package com.ape.mapsa.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.ActivitiTaskAlreadyClaimedException;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;

import com.ape.mapsa.bpm.service.IBPMService;
import com.ape.mapsa.model.Role;
import com.ape.mapsa.model.User;
import com.ape.mapsa.model.UserRole;
import com.ape.mapsa.service.IUserService;

@ManagedBean(name = "notificationMB")
@ViewScoped
public class NotificationBean implements Serializable {

	private static final long serialVersionUID = -1977508801914942345L;

	private static final Logger log = Logger.getLogger(NotificationBean.class);

	@ManagedProperty(value = "#{UserService}")
	IUserService userService;

	@ManagedProperty(value = "#{BPMService}")
	IBPMService bpmService;

	private List<Task> tasks = new ArrayList<Task>();
	private static List<Role> roles;

	private String userId;

	@PostConstruct
	public void getProdHome() {
		log.info("Initializing notification bean");
		initilizeMenu();
	}

	public void claimTask(String taskId) {
		log.info("Reclamando la tarea " + taskId + " para el usuario " + userId);
		try {
			bpmService.claimTask(taskId, userId);
			initilizeMenu();
		} catch (ActivitiObjectNotFoundException ex) {
			log.error(ex);
		} catch (ActivitiTaskAlreadyClaimedException claimed) {
			log.error(claimed);
		}
	}

	protected void initilizeMenu() {
		userId = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
		log.info("User: " + userId);
		if (userId != null) {
			User userByEmail = userService.getUserByEmail(userId);
			roles = new ArrayList<Role>();
			List<UserRole> userRoles = userByEmail.getRoles();
			if (userRoles != null) {
				for (UserRole userRole : userRoles) {
					roles.add(userRole.getRole());
				}
			}
			log.info("ROLES: " + roles);

			List<String> rolesString = new ArrayList<String>();
			for (UserRole userRole : userRoles) {
				rolesString.add(userRole.getRole().getRoleName());
			}
			tasks = new ArrayList<Task>();
			tasks.addAll(bpmService.getTasksByUser(userId));
			tasks.addAll(bpmService.getTasksByGroup(rolesString));
		}
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void setTasks(List<Task> tasks) {
		this.tasks = tasks;
	}

	public IBPMService getBpmService() {
		return bpmService;
	}

	public void setBpmService(IBPMService bpmService) {
		this.bpmService = bpmService;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
}
